<?php
/**
 * Created by xiaokengge
 * User: zhaoyu
 * Date: 2024/1/20
 * Time: 19:05
 *describe:****
 */

namespace app\common\service;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use app\api\service\ThrowNewErr;
use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;
use think\Cache;
use think\Exception;
class ALiSendService
{
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return OpenApiClient Client
     */


    public static function createClient(){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => 'LTAI4G4EMY7sGSNADpp3pZpK',
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => "oOH2np58oQSIuIqLBDElipnyfDSUQF"
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * API 相关
     * @return Params OpenApi.Params
     */
    public static function createApiInfo()
    {
        $params = new Params([
            // 接口名称
            "action" => "SendSms",
            // 接口版本
            "version" => "2017-05-25",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "POST",
            "authType" => "AK",
            "style" => "RPC",
            // 接口 PATH
            "pathname" => "/",
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        return $params;
    }

    /**
     * @param string[] $args
     * @return bool
     */
    public static function main($mobile)
    {
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient();
//        $params = self::createApiInfo();

        $sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        $sms_time = 600;
        // query params
//        $queries["PhoneNumbers"] = $mobile;
//        $queries["SignName"] = "双渔";
//        $queries["TemplateCode"] = "SMS_205408264";
//        $queries['templateParam']='{"code":"'.$sms_code.'"}' ;
//        // runtime options
//        $runtime = new RuntimeOptions([]);
//        $request = new OpenApiRequest([
//            "query" => OpenApiUtilClient::query($queries)
//        ]);
//        // 复制代码运行请自行打印 API 的返回值
//        // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
//        $res = $client->callApi($params, $request, $runtime);
//
//        if (strtolower($res['body']['Message']) != 'ok') {
//            (new ThrowNewErr())->validateFailException('阿里云平台返回错误_' . $res['body']['Message']);
//        }
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => "双渔",
            "templateCode" => "SMS_205408264",
            "templateParam" => '{"code":'.$sms_code.'}'
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
           $res= $client->sendSmsWithOptions($sendSmsRequest, $runtime);
           if(strtoupper($res->body->message) != "OK"){
               (new ThrowNewErr())->validateFailException('阿里云平台返回错误_' . $res->body->message );
           }
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            Utils::assertAsString($error->message);
        }

        Cache::set($mobile, $sms_code, $sms_time);
        return true;
    }

}

